package com.running.base.run.mq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RabbitMqSender {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMqSender.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    logger.info("发送成功！消息 ID: {}", correlationData != null ? correlationData.getId() : "无");
                } else {
                    logger.error("发送失败！消息 ID: {}，原因: {}", correlationData != null ? correlationData.getId() : "无", cause);
                }
            }
        });
        logger.info("注册rabbitmq-confirm 完成！");

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                // 处理消息无法路由的情况
                logger.error("消息无法路由到队列:");
                logger.error("消息: " + new String(message.getBody()));
                logger.error("回复码: " + replyCode);
                logger.error("回复文本: " + replyText);
                logger.error("交换机: " + exchange);
                logger.error("路由键: " + routingKey);
            }
        });
        logger.info("注册rabbitmq-setReturnCallback 完成！");
    }

    public void doSendMqMsg(String msg) {
        logger.info("doSendMqMsg准备投递消息：{}", msg);
        try {
            rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_NAME, RabbitmqConfig.ROUTE_NAME, msg);
        } catch (Exception e) {
            logger.error("doSendMqMsg消息发送异常：", e);
        }

    }

}
